package controller;

import exception.OtherException;
import exception.SomeException;
import exception.UserExistException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

/**
 * Author:shixiaojun@itany.com
 * Date:2022/5/23 10:23
 * Version:1.0-SNAPSHOT
 * Description:
 */
@Controller
@RequestMapping("/exception")
public class ExceptionController {

//    @ExceptionHandler(SomeException.class)
//    public ModelAndView exceptionHandler(Exception e){
//        ModelAndView mav = new ModelAndView();
//        mav.setViewName("exception");
//        mav.addObject("msg",e);
//        return mav;
//    }
//
//    @ExceptionHandler(OtherException.class)
//    public ModelAndView exceptionHandler2(Exception e){
//        ModelAndView mav = new ModelAndView();
//        mav.setViewName("exception2");
//        mav.addObject("msg",e);
//        return mav;
//    }


    @ExceptionHandler
    public ModelAndView exceptionHandler(Exception e){
        ModelAndView mav = new ModelAndView();
        if(e instanceof SomeException){
            mav.setViewName("exception");
        } else if(e instanceof OtherException){
            mav.setViewName("exception2");
        } else{
            mav.setViewName("globalException");
        }
        mav.addObject("msg",e);
        return mav;
    }


    @RequestMapping("/f1")
    public void f1() throws SomeException {
        System.out.println("ExceptionController.f1");
        throw new SomeException("执行f1方法遇到了异常");
    }

    @RequestMapping("/f2")
    public void f2() throws OtherException {
        System.out.println("ExceptionController.f2");
        throw new OtherException("执行f2方法遇到了异常");
    }

    @RequestMapping("/f3")
    public void f3() throws UserExistException {
        System.out.println("ExceptionController.f3");
        throw new UserExistException("该用户已经被注册");
    }

}
